package 反射;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;

@Slf4j
public class Reflection {

    public static void main(String[] args) throws NoSuchFieldException, ClassNotFoundException, IllegalAccessException, InstantiationException {
//        test1();

        Student student = new Student("luyi");
        getPrivateField(student);
    }

    private static void test1() throws IllegalAccessException, NoSuchFieldException, InstantiationException, ClassNotFoundException {
        Class studentClazz = Class.forName("反射.Student");
        // 获取学生对象
        Object stuObject = studentClazz.newInstance();

        // 获取私有的字段对象
        Field field = studentClazz.getDeclaredField("name");
        //设置反射时，取消Java的访问检查，暴力访问
        field.setAccessible(true);

        // 调用 private 的 get/set
        field.set(stuObject, "张从龙");

        System.out.println("获取的子段名：" + field);
        System.out.println("获取到的字段：" + field.get(stuObject));
    }


    private static void getPrivateField(Student student) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
        Class studentClazz = Class.forName("反射.Student");
        //获取私有的字段对象
        Field field = studentClazz.getDeclaredField("name");
        //设置反射时，取消Java的访问检查，暴力访问
        field.setAccessible(true);
        System.out.println("获取的子段名：" + field.get(student));
    }
}
